﻿using System;
using System.Workflow.ComponentModel;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Workflow;
using System.Diagnostics;

namespace CrmContrib.Workflow.Activities.Utilities
{
    [CrmWorkflowActivity("Format DateTime", "CrmContrib \\ Utilities")]
    public partial class FormatDateTimeActivity : Activity
    {
        [CrmInput("DateTime Input")]
        public CrmDateTime DateTimeInput
        {
            get { return (CrmDateTime)GetValue(DateTimeInputProperty); }
            set { SetValue(DateTimeInputProperty, value); }
        }

        public static readonly DependencyProperty DateTimeInputProperty = DependencyProperty.Register("DateTimeInput", typeof(CrmDateTime), typeof(FormatDateTimeActivity));


        [CrmInput("DateTime Format")]
        public string DateTimeFormat
        {
            get { return (string)GetValue(DateTimeFormatProperty); }
            set { SetValue(DateTimeFormatProperty, value); }
        }

        public static readonly DependencyProperty DateTimeFormatProperty = DependencyProperty.Register("DateTimeFormat", typeof(string), typeof(FormatDateTimeActivity));

        [CrmOutput("DateTime Formatted")]
        public string DateTimeFormatted
        {
            get { return (string)GetValue(DateTimeFormattedProperty); }
            set { SetValue(DateTimeFormattedProperty, value); }
        }

        public static readonly DependencyProperty DateTimeFormattedProperty = DependencyProperty.Register("DateTimeFormatted", typeof(string), typeof(FormatDateTimeActivity));


        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            try
            {
                if ((!string.IsNullOrEmpty(this.DateTimeFormat)) && (this.DateTimeInput != null))
                {
                    this.DateTimeFormatted = DateTime.Parse(this.DateTimeInput.Value).ToString(this.DateTimeFormat);
                }
                else
                {
                    this.DateTimeFormatted = "";
                }
            }
            catch(Exception ex)
            {
                Trace.TraceWarning(string.Format("The DateTime property could not be formatted ({0})", ex.Message));
                var dateTimeValue = this.DateTimeInput != null ? this.DateTimeInput.Value.ToString() : "";
                this.DateTimeFormatted = dateTimeValue;
            }
            return base.Execute(executionContext);
        }
    }
}